package com.xingzhe.content.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xingzhe.base.exception.XingZhePlusException;
import com.xingzhe.content.mapper.CourseBaseMapper;
import com.xingzhe.content.mapper.CourseTeacherMapper;
import com.xingzhe.content.model.po.CourseBase;
import com.xingzhe.content.model.po.CourseTeacher;
import com.xingzhe.content.service.CourseTeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {
    @Resource
    private CourseTeacherMapper courseTeacherMapper;
    @Resource
    private CourseBaseMapper courseBaseMapper;
    @Override
    public List<CourseTeacher> findAll(Long courseId) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId);
        return courseTeacherMapper.selectList(queryWrapper);
    }

    @Transactional
    @Override
    public void saveOrUpdateCourseTeacher(CourseTeacher teacher,Long companyId) {
        Long courseId = teacher.getCourseId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (!Objects.equals(courseBase.getCompanyId(), companyId)){
            XingZhePlusException.cast("只能修改自己机构的课程!");
            return;
        }
        Long id = teacher.getId();
        //如果是没有教师id则证明是新增教师
        if (id==null){
            teacher.setCreateDate(LocalDateTime.now());
            courseTeacherMapper.insert(teacher);
        }
        //有教师id，则是修改改教师的信息
        CourseTeacher courseTeacherNew = new CourseTeacher();
        BeanUtils.copyProperties(teacher,courseTeacherNew);
        courseTeacherMapper.updateById(courseTeacherNew);
    }

    @Transactional
    @Override
    public void deleteCourseTeacher(Long courseId, Long teacherId,Long companyId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (!Objects.equals(courseBase.getCompanyId(), companyId)){
            XingZhePlusException.cast("只能修改自己机构的课程!");
            return;
        }

        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId)
                .eq(CourseTeacher::getId,teacherId);
        courseTeacherMapper.delete(queryWrapper);
    }

}
